package cn.Controller;

import cn.Mapper.CommentMapper;
import cn.Service.UserService;
import cn.entity.Comment;
import cn.entity.Order;
import cn.entity.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class CommentController {
    @Autowired
    private UserService userService;
    @Autowired
    private CommentMapper commentMapper;
    @RequestMapping("/AddCommentBy")
    public String AddCommentBy(@RequestParam("file") MultipartFile multipartFile, Comment comment,HttpServletRequest req) throws IOException {
        String oldname = multipartFile.getOriginalFilename();
        int i = oldname.lastIndexOf(".");
        String substring = oldname.substring(i);
        String string = UUID.randomUUID().toString();
        String newName=string+substring;
        File file=new File("F://WorkSpace/ssm-development-master/src/main/web/product/touxiang");
        if (!file.exists()){
            file.mkdirs();
        }
        String path=file+"/"+newName;
        multipartFile.transferTo(new File(path));
        String imgs="product/touxiang/"+newName;
        if (comment.getScore()==null||comment.getScore()==0){
            comment.setScore(1);
        }
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        List<OrderItem> ordersslist = (List<OrderItem>) req.getSession().getAttribute("ordersslist");
        for (OrderItem orderItem : ordersslist) {
            comment.setPid(orderItem.getPid());
            String format = sdf.format(date);
            comment.setCmtime(format);
            comment.setCmimage(imgs);
            commentMapper.AddCommentBy(comment);
            System.out.println(comment.toString());
        }
        return "forward:getOrders.do";
    }
    @RequestMapping("/FindProductByOid")
    public String FindProductByOid(Integer oid, HttpServletRequest req){
        req.getSession().removeAttribute("ordersslist");
        List<OrderItem> ordersslist = commentMapper.FindPidByOid(oid);
        req.getSession().setAttribute("ordersslist",ordersslist);
        userService.updateOstate3(oid);
        return "comment";
    }
}
